//
//  TJChatController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJChatController.h"
#import "HJInputController.h"
#import "HJIM.h"
#import "HJChatMessageLayoutHeader.h"
#import "TUIDefine.h"
#import "HJSingleChatController.h"
#import "HJGroupChatController.h"
#import "HJChatMessageVoiceCell.h"
#import "HJChatMessageImageCell.h"
#import "HJChatMessageVideoCell.h"
#import "HJChatMessageModel.h"
#import "HJAlertController.h"
#import "HJSelectFile.h"
#import "HJPhotoBrowser.h"
#import "HJUserInfoController.h"
#import "HJNavigationController.h"
#import "HJPayTransferController.h"
#import "HJPayTransferDetailController.h"
#import "HJVideoPlayController.h"

@interface HJChatController ()<HJInputControllerDelegate, TJMessageControllerDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate>


@property (nonatomic, weak) HJInputController *inputController;

@property (nonatomic, assign) BOOL responseKeyboard;
@property (nonatomic, assign) BOOL firstAppear;
@property (nonatomic, assign) BOOL hasClearReadFire;
@property (nonatomic, strong) HJSelectFile *selectFile;


@end

@implementation HJChatController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = self.sessionModel.sessionName;
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    
    IQKeyboardManager.sharedManager.enable = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self addMessageController];
    [self addInputController];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleReceiveNewMessageNotification:) name:receiveNewMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSendMessageCompleteNotification:) name:sendMessageCompleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSendMessageStatusChangeNotification:) name:sendMessageStatusChangeNotification object:nil];
    [self readMessage];
}

- (void)handleSendMessageStatusChangeNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    if (messageModel.msgStatus == HJMessageStatusSending) {
        [self updateMessage:messageModel];
    }
}

- (void)handleSendMessageCompleteNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    [self updateMessage:messageModel];
}

- (void)readMessage {
    [HJIM.shareIM.conversationManager readMessageWithSessionId:_sessionModel.sessionId msgIds:nil completion:nil];
}

+ (instancetype)chatControllerWithSessionModel:(HJChatSessionModel *)sessionModel {
    HJChatController *chatController = nil;
    if (sessionModel.chatType == HJChatTypeGroup) {
        chatController = [[HJGroupChatController alloc] init];
    } else if (sessionModel.chatType == HJChatTypeSingle) {
        chatController = [[HJSingleChatController alloc] init];
    }
    chatController.sessionModel = sessionModel;
    return chatController;
}


+ (void)showWithSessionModel:(HJChatSessionModel *)sessionModel {
    
    UINavigationController *navigationController = HJTools.currentNavController;
    
    HJChatSessionModel *existSessionModel = nil;
      for (UIViewController *viewController in HJTools.currentNavController.viewControllers) {
          if ([viewController isKindOfClass:HJChatController.class]) {
              HJChatController *chatController = (HJChatController *)viewController;
              existSessionModel = chatController.sessionModel;
          }
      }
  
      if (existSessionModel) {
          if (existSessionModel.chatType == HJChatTypeSingle && !TJIM_isSelf(sessionModel.sessionUserd)) {
              [navigationController popViewControllerAnimated:YES];
          } else {
              HJChatController *chatController = [HJChatController chatControllerWithSessionModel:sessionModel];
              [navigationController pushViewController:chatController];
              navigationController.viewControllers = @[navigationController.viewControllers.firstObject, chatController];
          }
      } else {
          HJChatController *chatController = [HJChatController chatControllerWithSessionModel:sessionModel];
          [navigationController pushViewController:chatController];
      }
}


- (void)addMessageController {
    
    HJMessageController *messageController = [[HJMessageController alloc] init];
    messageController.sessionModel = self.sessionModel;
    messageController.delegate = self;
    [self addChildViewController:messageController];
    [self.view addSubview:messageController.view];
    [messageController didMoveToParentViewController:self];
    messageController.view.frame = CGRectMake(0, KNavBarHight,
                                              self.view.frame.size.width,
                                              self.view.frame.size.height - TTextView_Height - TabbarSafeBottomMargin - KNavBarHight);
    
    _messageController = messageController;
}

- (void)addInputController {
    HJInputController *inputController = [[HJInputController alloc] init];
    inputController.delegate = self;
    inputController.sessionUserd = self.sessionModel.sessionUserd;
    if (self.sessionModel.chatType == HJChatTypeGroup) {
        inputController.groupId = self.sessionModel.sessionId ?: self.sessionModel.groupId;
    }
    [self addChildViewController:inputController];
    [self.view addSubview:inputController.view];
    inputController.view.frame = CGRectMake(0, self.view.frame.size.height - (TTextView_Height + TabbarSafeBottomMargin),
                                            self.view.frame.size.width,
                                            TTextView_Height + TabbarSafeBottomMargin);
    _inputController = inputController;
}

- (void)didTapInMessageController:(HJMessageController *)controller {
    [self.inputController reset];
}

- (void)messageControllerNeedResetInput:(HJMessageController *)controller {
    [self.inputController reset];
}

- (void)messageController:(HJMessageController *)controller onSelectMessageAvatar:(HJChatMessageCell *)cell {
    HJUserInfoController *userInfoController = [[HJUserInfoController alloc] init];
    userInfoController.userId = cell.messageLayout.messageModel.senderId;
    [self.navigationController pushViewController:userInfoController];
}

- (void)messageController:(HJMessageController *)controller onLongSelectMessageAvatar:(HJChatMessageCell *)cell {
    
    
}


- (void)messageController:(HJMessageController *)controller didClickRetryButton:(HJChatMessageCell *)cell {
    HJChatMessageLayout *messageLayout = cell.messageLayout;
    HJChatMessageModel *messageModel = messageLayout.messageModel;
    [self sendMessageWithModel:messageModel];
}

- (void)messageController:(HJMessageController *)controller onSelectMessageContent:(HJChatMessageCell *)cell {
    
    HJChatMessageLayout *messageLayout = cell.messageLayout;
    
    if (messageLayout.messageModel.messageType == HJMessageTypeVideo) {
        HJVideoPlayController *videoPlayController = [[HJVideoPlayController alloc] init];
        videoPlayController.url = messageLayout.messageModel.fileUrl;
        if ([[NSFileManager defaultManager] fileExistsAtPath:messageLayout.messageModel.localPath]) {
            NSLog(@"存在本地路径");
        }
        NSLog(@"messageLayout.messageModel.localPath = %@", messageLayout.messageModel.localPath);
        videoPlayController.localPath = messageLayout.messageModel.localPath;
        [self presentViewController:videoPlayController animated:YES completion:nil];
        return;
    }
    
    
    if (messageLayout.messageModel.messageType == HJMessageTypeTransfer) {
        messageLayout.messageModel.isReadDetail = YES;
        cell.messageLayout = messageLayout;
        [messageLayout.messageModel bg_saveOrUpdateAsync:nil];
        HJPayTransferDetailController *payTransferDetailController = [[HJPayTransferDetailController alloc] init];
        payTransferDetailController.messageModel = messageLayout.messageModel;
        payTransferDetailController.sessionModel = self.sessionModel;
        [self.navigationController pushViewController:payTransferDetailController];
        return;
    }
    
    if (messageLayout.messageModel.messageType == HJMessageTypeVoice) {
        
        HJChatMessageVoiceLayout *selectVoiceLayout = (HJChatMessageVoiceLayout *)messageLayout;
        if (selectVoiceLayout.isPlaying) {
            [selectVoiceLayout stopVoiceMessage];
        } else {
            for (HJChatMessageLayout *cellLayout in self.messageController.messageLayouts) {
                if (cellLayout.messageModel.messageType != HJMessageTypeVoice) {
                    continue;
                }
                HJChatMessageVoiceLayout *voiceLayout = (HJChatMessageVoiceLayout *)cellLayout;
                [voiceLayout stopVoiceMessage];
            }
            
            HJChatMessageVoiceLayout *voiceLayout = (HJChatMessageVoiceLayout *)messageLayout;
            [voiceLayout playVoiceMessage];
            cell.messageLayout.messageModel.voiceRead = @"1";
            ((HJChatMessageVoiceCell *)cell).voiceReadPointView.hidden = YES;
            [cell.messageLayout.messageModel bg_saveOrUpdate];
        }
        return;
    }
    
    [self.inputController reset];
    if (messageLayout.messageModel.messageType == HJMessageTypeImage || messageLayout.messageModel.messageType == HJMessageTypeVideo) {
        
        NSMutableArray *mediaDatas = [NSMutableArray array];
        NSMutableArray *Marr = [NSMutableArray array];
        [self.messageController.messageLayouts enumerateObjectsUsingBlock:^(HJChatMessageLayout *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj.messageModel.messageType == HJMessageTypeImage || obj.messageModel.messageType == HJMessageTypeVideo) {
                [mediaDatas addObject:obj];
                
                HJChatMessageImageCell *souceCell = nil;
                for (HJChatMessageCell *visibleCell in self.messageController.tableView.visibleCells) {
                    if (visibleCell.messageLayout == obj || visibleCell.messageLayout.messageModel.msgId == obj.messageModel.msgId) {
                        souceCell = (HJChatMessageImageCell *)visibleCell;
                        break;
                    }
                }
                
                HJPhotoItem *item = [HJPhotoItem itemWithMessageModel:obj.messageModel];
                item.sourceView = souceCell.containerView;
                item.thumbImage = souceCell.contentImageView.image;
                [Marr addObject:item];
            }
        }];
        
        NSInteger index = [mediaDatas indexOfObject:messageLayout];
        HJPhotoBrowser *browser = [HJPhotoBrowser browserWithPhotoItems:Marr selectedIndex:index];
        [browser showFromViewController:self];
        return;
    }
}


- (void)inputController:(HJInputController *)inputController didSelectMoreCell:(HJInputMoreCell *)cell {
    
    TJWeakify(self)
    if ([cell.data.key isEqualToString:@"camera"]) {
        [self.selectFile openCameraInController:self complete:^(id  _Nonnull mediaObject) {
            if ([mediaObject isKindOfClass:UIImage.class]) {
                
                NSData *imageData = UIImageJPEGRepresentation(mediaObject, 0.6);
                UIImage *originalImage = [UIImage imageWithData:imageData];
                
                NSString *fileName = getFileNameWithPathExtension(@"jpg");;
                NSString *localPath = [HJMessageFileManager imagefileFilePathWithSessionId:weakself.sessionModel.sessionId fileName:fileName];
                BOOL res = [HJTools writeImageData:imageData toLocalPath:localPath];
                if (res) {
                    [weakself sendImageMessageByLocalPath:localPath photo:originalImage];
                }
                
            }
        }];
    }
    
    if ([cell.data.key isEqualToString:@"album"]) {
        [self.selectFile selectPhotoInController:self complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets) {
            [self sendMediaMessageByAssets:assets photo:photos];
        }];
    }
    
    if ([cell.data.key isEqualToString:@"transfer"]) {
//        [self.inputController reset];
        HJPayTransferController *payTransferController = [[HJPayTransferController alloc] init];
        payTransferController.sessionModel = self.sessionModel;
        HJNavigationController *navigationController = [[HJNavigationController alloc] initWithRootViewController:payTransferController];
        [self presentViewController:navigationController animated:YES completion:nil];
    }
    
}

- (void)popViewController {
    [super popViewController];
    
    dispatch_async_queue(^{
        [self.messageController.messageLayouts enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(HJChatMessageLayout * _Nonnull messageLayout, NSUInteger idx, BOOL * _Nonnull stop) {
            if (messageLayout.messageModel.messageType == HJMessageTypeImage && messageLayout.messageModel.msgStatus == HJMessageStatusSending) {
                [messageLayout.messageModel bg_saveOrUpdateAsync:nil];
            }
        }];
    });
}

- (void)inputController:(HJInputController *)inputController didChangeHeight:(CGFloat)height {
    
    if (!self.responseKeyboard) {
        return;
    }
    
    UIViewAnimationOptions animationOptions = 7 << 16;
    [UIView animateWithDuration:0.25 delay:0 options:animationOptions animations:^{
        CGRect msgFrame = self.messageController.view.frame;
        msgFrame.size.height = self.view.frame.size.height - KNavBarHight - height;
        self.messageController.view.frame = msgFrame;
        
        CGRect inputFrame = self.inputController.view.frame;
        inputFrame.origin.y = msgFrame.origin.y + msgFrame.size.height;
        inputFrame.size.height = height;
        self.inputController.view.frame = inputFrame;
        
        [self.messageController scrollToBottom:NO];
        
    } completion:nil];
    
}

- (void)inputController:(HJInputController *)inputController didSendTextMessage:(NSString *)text {
    [self sendTextMessageByText:text];
}

- (void)inputController:(HJInputController *)inputController didSendVoiceMessage:(NSString *)localPath {
    [self sendVoiceMessageByLocalPath:localPath];
}

- (HJChatMessageModel *)getMessageModel {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = self.sessionModel.chatType;
    if (messageModel.chatType == HJChatTypeSingle) {
        messageModel.sessionUserd = self.sessionModel.sessionUserd;
        messageModel.sessionId = self.sessionModel.sessionId;
        messageModel.receiverId = self.sessionModel.sessionUserd;
        if (!messageModel.receiverId) {
            messageModel.receiverId = TJIM_isSelf(self.sessionModel.senderId) ? self.sessionModel.receiveId : self.sessionModel.uid;
        }
    } else {
        messageModel.groupId = self.sessionModel.sessionId;
    }
    return messageModel;
}

- (void)sendTextMessageByText:(NSString *)text {
    HJChatMessageModel *messageModel = [self getMessageModel];
    messageModel.messageType = HJMessageTypeText;
    messageModel.content = text;
    [self sendMessageWithModel:messageModel];
}

- (void)sendMediaMessageByAssets:(NSArray<PHAsset *> *)asset photo:(NSArray<UIImage *> *)photo {
    dispatch_async_queue(^{
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        for (int i = 0; i < asset.count; i++) {
//            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            [self sendMediaMessageByAsset:asset[i] photo:photo[i] completion:^{
//                dispatch_semaphore_signal(semaphore);
            }];
        }
    });
}

- (void)sendMediaMessageByAsset:(PHAsset *)asset photo:(UIImage *)photo completion:(void (^)(void))completion {
    
    HJChatMessageModel *messageModel = [self getMessageModel];
    messageModel.asset = asset;
    messageModel.originalImage = photo;
    [[HJIM shareIM].chatManager sendMessageWithModel:messageModel begin:^{
        [self addNewMessage:messageModel];
        completion();
    } completion:^(id  _Nullable response, NSError * _Nullable error) {
        [self updateMessage:messageModel];
    }];
}

- (void)sendVideoMessageByLocalPath:(NSString *)localPath photo:(UIImage *)photo {
    HJChatMessageModel *messageModel = [self getMessageModel];
    messageModel.messageType = HJMessageTypeVideo;
    messageModel.localPath = localPath;
    messageModel.originalImage = photo;
    [self sendMessageWithModel:messageModel];
}

- (void)sendImageMessageByLocalPath:(NSString *)localPath photo:(UIImage *)photo{
    HJChatMessageModel *messageModel = [self getMessageModel];
    messageModel.messageType = HJMessageTypeImage;
    messageModel.localPath = localPath;
    messageModel.originalImage = photo;
    [self sendMessageWithModel:messageModel];
}

- (void)sendFileMessageByUrl:(NSURL *)URL{
    
}

- (void)sendVoiceMessageByLocalPath:(NSString *)localPath {
    HJChatMessageModel *messageModel = [self getMessageModel];
    messageModel.messageType = HJMessageTypeVoice;
    messageModel.localPath = localPath;
    [self sendMessageWithModel:messageModel];
}

- (void)sendMessageWithModel:(HJChatMessageModel *)messsageModel {
    [[HJIM shareIM].chatManager sendMessageWithModel:messsageModel begin:^{
        [self addNewMessage:messsageModel];
    } completion:^(id  _Nullable response, NSError * _Nullable error) {
    }];
}

- (void)handleReceiveNewMessageNotification:(NSNotification *)not {
    dispatch_async_main_queue(^{
        HJChatMessageModel *messageModel = not.object;
        if (![self.navigationController.viewControllers containsObject:self]) return;
        
        if ([messageModel.sessionId isEqualToString:self.sessionModel.sessionId]) {
            [self didReceiveNewMessage:messageModel];
        }
    });
}

- (void)didReceiveNewMessage:(HJChatMessageModel *)messageModel {
    HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
    [HJIM.shareIM.conversationManager readMessageWithSessionId:messageModel.sessionId msgIds:@[messageModel.serverMsgId] completion:nil];
    [self.messageController addNewMessage:messageLayout];
}

- (void)addNewMessage:(HJChatMessageModel *)messageModel {
    
    HJChatMessageLayout *bindingTipMessageLayout = nil;
    if (messageModel.isRetry) {
        HJChatMessageLayout *messageLayout = nil;
        for (HJChatMessageLayout *layout in [self.messageController.messageLayouts reverseObjectEnumerator]) {
            if ([layout.messageModel.msgId isEqualToString:messageModel.msgId]) {
                messageLayout = layout;
                break;
            }
        }
        
        if (messageLayout) {
            [self.messageController.messageLayouts removeObject:messageLayout];
        }
        
        dispatch_async_sql_queue(^{
            [HJIM.shareIM.messageManager deleteMessageWithMessageModel:messageModel];
        });
    }
    
    if (messageModel.bindingTipMsgId) {
        for (HJChatMessageLayout *layout in [self.messageController.messageLayouts reverseObjectEnumerator]) {
            if ([layout.messageModel.msgId isEqualToString:messageModel.bindingTipMsgId]) {
                bindingTipMessageLayout = layout;
                break;
            }
        }
        
        if (bindingTipMessageLayout) {
            [self.messageController.messageLayouts removeObject:bindingTipMessageLayout];
            dispatch_async_sql_queue(^{
                [HJIM.shareIM.messageManager deleteMessageWithMessageModel:bindingTipMessageLayout.messageModel];
            });
        }
    }
    
    HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
    [self.messageController addNewMessage:messageLayout];
}

- (void)updateMessage:(HJChatMessageModel *)messageModel {
    [self.messageController updateMessage:messageModel];
}

- (void)inputControllerDidInputAt:(HJInputController *)inputController {}
- (void)inputController:(HJInputController *)inputController didDeleteAt:(NSString *)atText {}

- (HJSelectFile *)selectFile {
    if (!_selectFile) {
        _selectFile = [[HJSelectFile alloc] init];;
    }
    return _selectFile;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    IQKeyboardManager.sharedManager.enable = NO;
    
    self.responseKeyboard = YES;
    if (self.firstAppear) {
        self.firstAppear = NO;
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    IQKeyboardManager.sharedManager.enable = YES;
    self.responseKeyboard = NO;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    TJLog(@"%s", __func__);
}



@end
